package cmd

import (
	"hxy/repo/config"
	"os"
	"os/exec"
	"strings"
	"time"

	"github.com/google/uuid"
)

// TODO: 考虑加个logpath来指定log名称
type PipelineTask struct {
	ID        uuid.UUID `gorm:"primarykey" json:"id"`
	Git_id    int       `json:"git_id"`
	RunProg   string    `json:"programme"`
	Command   string    `json:"command"`
	Dir       string    `json:"dir"`
	State     string    `json:"state"`
	BeginTime time.Time `json:"begin_time"`
	EndTime   time.Time `json:"end_time"`
	GitHash   string    `json:"git_hash"`
}
type RunCommand struct {
	Git_id  int    `json:"Git_id"`
	GitHash string `json:"GitHash"`
	RunProg string `json:"RunProg"`
	Command string `json:"Command"`
	Dir     string `json:"Dir"`
}

// Function  PipelineTask.Run() will exec the compile task
// The Compile task's log will store in the /logpath-in-config/{task.UUID}.log
func (task PipelineTask) Run() error {
	maven, errs := exec.LookPath(task.RunProg)
	if errs != nil {
		return errs
	}
	cmd := exec.Command(maven, strings.Split(task.Command, " ")...)
	cmd.Dir = task.Dir
	//TODO 这里的文件名称需要考虑一下
	_log, err := os.Create(config.ComplierLogPath + task.ID.String() + ".log")
	if err != nil {
		return err
	}
	cmd.Stdout = _log
	cmd.Stderr = _log

	err = cmd.Run()
	if err != nil {

		return err
	}
	return nil

}
func (task *PipelineTask) Build(parame interface{}) error {
	runcommand := parame.(*RunCommand)
	task.ID = uuid.New()
	task.Git_id = runcommand.Git_id
	task.GitHash = runcommand.GitHash
	task.RunProg = runcommand.RunProg
	task.Command = runcommand.Command
	task.Dir = runcommand.Dir
	return nil
}
